package weifei.live.simulation.interceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import weifei.live.simulation.entity.ChatGroup;
import weifei.live.simulation.service.UserService;

import java.io.PrintWriter;

public class GroupOwnerInterceptor implements HandlerInterceptor
{
    private final UserService userService = new UserService();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception
    {
        var token = request.getHeader("token");
        var user_id = this.userService.getUserIDByToken(token);

        var groupId = request.getParameter("id");
        if (groupId == null)
            groupId = request.getParameter("groupId");
        if (groupId == null)
            return false;

        Integer id = null;
        try {
            id = Integer.decode(groupId);
        } catch (Exception e) {
            PrintWriter out = response.getWriter();
            out.println("参数错误");
            return false;
        }

        ChatGroup target = new ChatGroup(id).selectById();
        if (target == null) {
            PrintWriter out = response.getWriter();
            out.println("不存在的群聊");
            return false;
        }
        if (!target.getOwnerId().equals(user_id))
        {
            PrintWriter out = response.getWriter();
            out.println("没有权限");
            return false;
        }

        return true;
    }
}

